<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2006
sirfragalot@users.sourceforge.net
**********************************************************************************/
/*****
* LISTMETADATACOMMON class
*
* Common methods for searching and selecting metadata
*****/
class LISTMETADATACOMMON
{
// Constructor
	function LISTMETADATACOMMON($db, $vars, $output)
	{
		$this->db = $db;
		$this->vars = $vars;
		$this->output = $output;
		include_once("core/html/TABLE.php");
		include_once("core/html/MISC.php");
		include_once("core/session/SESSION.php");
		$this->session = new SESSION();
		if($this->output == 'rtf')
			$this->session->setVar("exportRtf_style", $this->session->getVar("setup_style"));
		include_once("core/styles/BIBSTYLE.php");
		$this->bibStyle = new BIBSTYLE($this->db, $this->output);
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/wp/WPRTF.php");
		$this->wprtf = new WPRTF();
		include_once("core/cite/CITE.php");
		$this->cite = new CITE($this->db, $this->vars);
		include_once("core/html/HTML.php");
		$this->html = new HTML();
		include_once("core/html/FORM.php");
		include_once("core/user/USER.php");
		$this->user = new USER($this->db);
		include_once("core/icons/LOADICONS.php");
		$this->icons = new LOADICONS();
		$this->icons->getIconInfo("view");
		$this->viewEditLink = $this->icons->viewExists ? "imgLink" : "link";
		include_once("core/sql/STATEMENTS.php");
		$stmt = new STATEMENTS($this->db);
		$this->baseSql = $this->db->selectNoExecute(array("WKX_resource"), $stmt->listFields(),
			$stmt->selectJoin());
		$this->resourceTitles = array();
		$this->quotes = $this->paraphrases = $this->quoteComments = $this->paraphraseComments = 
			$this->musings = array();
		$this->quoteCommentUserId = $paraphraseCommentUserId = $this->musingUserId = $this->userArray = array();
		$this->quotePages = $this->quoteCommentPages = $this->paraphrasePages = 
			$this->paraphraseCommentPages = $this->musingPages = array();
		$this->suwpCite = FALSE; // If TRUE, this is metadata insert popup from SUWP
		$this->radioButtonFirst = TRUE;
		$this->citeIndex = 1;
	}
// Grab resource from database
	function grabResource($id)
	{
		$sql = $this->baseSql . " WHERE WKX_resource.id=" . $this->db->tidyInput($id);
		$recordset = $this->db->query($sql);
		if(!$this->db->numRows($recordset))
			return FALSE;
		return $this->bibStyle->process($this->db->fetchRow($recordset));
	}
// Execute a SQL statement for a particular metadata field
	function executeThisStmt($stmt, $textField, $field, &$allIds, $userId, $patterns = FALSE)
	{
		$this->patterns = $patterns;
		$recordSet = $this->db->query($stmt);
		if($metadataCount = $this->db->numRows($recordSet))
		{
			while($row = $this->db->loopRecordSet($recordSet))
			{
				if((($field == 'quoteComments') && ($row['quotePrivate'] == 'Y') && 
					($userId != $row['addUserIdQuote']))
					||
					(($field == 'paraphraseComments') && ($row['paraphrasePrivate'] == 'Y') && 
					($userId != $row['addUserIdParaphrase']))
					||
					(($field == 'musings') && ($row['musingPrivate'] == 'Y') && 
					($userId != $row['addUserIdMusing']))
					)
					continue;
				if(($field == 'quotes') || ($field == 'quoteComments'))
					$fieldId = 'quoteId';
				else if(($field == 'paraphrases') || ($field == 'paraphraseComments'))
					$fieldId = 'paraphraseId';
				if(!array_key_exists($row['resourceId'], $this->resourceTitles))
					$this->resourceTitles[$row['resourceId']] = 
						$this->grabResource($row['resourceId']);
				if($field == 'quotes')
				{
					if($pages = $this->formatPages($row['page_start'], $row['page_end']))
						$this->quotePages[$row[$fieldId]] = $pages;
					else if($this->output == 'rtf')
						$this->quotePages[$row[$fieldId]] = '-->  ';
					$this->quoteCitePages[$row[$fieldId]] = $this->citePages;
					$this->{$field}[$row['resourceId']][$row[$fieldId]] = $row[$textField];
				}
				if($field == 'paraphrases')
				{
					if($pages = $this->formatPages($row['page_start'], $row['page_end']))
						$this->paraphrasePages[$row[$fieldId]] = $pages;
					else if($this->output == 'rtf')
						$this->paraphrasePages[$row[$fieldId]] = '-->  ';
					$this->paraphraseCitePages[$row[$fieldId]] = $this->citePages;
					$this->{$field}[$row['resourceId']][$row[$fieldId]] = $row[$textField];
				}
				else if($field == 'quoteComments')
				{
					if($pages = $this->formatPages($row['page_start'], $row['page_end']))
						$this->quoteCommentPages[$row['commentId']] = $pages;
					else if($this->output == 'rtf')
						$this->quoteCommentPages[$row['commentId']] = '-->  ';
					$this->{$field}[$row['resourceId']][$row[$fieldId]][$row['commentId']] = $row[$textField];
					$this->getUser($field, $row['commentId'], $row['addUserIdQuote']);
				}
				else if($field == 'paraphraseComments')
				{
					if($pages = $this->formatPages($row['page_start'], $row['page_end']))
						$this->paraphraseCommentPages[$row['commentId']] = $pages;
					else if($this->output == 'rtf')
						$this->paraphraseCommentPages[$row['commentId']] = '-->  ';
					$this->{$field}[$row['resourceId']][$row[$fieldId]][$row['commentId']] = $row[$textField];
					$this->getUser($field, $row['commentId'], $row['addUserIdParaphrase']);
				}
				else if($field == 'musings')
				{
					if($pages = $this->formatPages($row['page_start'], $row['page_end']))
						$this->musingPages[$row['commentId']] = $pages;
					else if($this->output == 'rtf')
						$this->musingPages[$row['commentId']] = '-->  ';
					$this->{$field}[$row['resourceId']][$row['commentId']] = $row[$textField];
					$this->getUser($field, $row['commentId'], $row['addUserIdMusing']);
				}
				if(!$this->suwpCite && array_search($row['resourceId'], $allIds) === FALSE)
					$allIds[] = $row['resourceId'];
			}
		}
		return $metadataCount;
	}
// Format pages
	function formatPages($start, $end)
	{
		$this->citePages = FALSE;
		if(!$start)
			return FALSE;
		if($this->suwpCite)
			$this->citePages = ":" . stripslashes($start);
		if(!$end)
		{
			if($this->output == 'html')
				return 'p.' . $start . ":&nbsp;&nbsp;";
			if($this->output == 'rtf')
				return "p." . $start . ":  ";
		}
		if($this->suwpCite)
			$this->citePages .= "-" . stripslashes($end);
		if($this->output == 'html')
			return 'pp.' . $start . '&ndash;' . $end . ":&nbsp;&nbsp;";
		if($this->output == 'rtf')
			return "pp." . $start . "\\u8212\\'14" . $end . ":  ";
	}
// Grab and format user names for comments and musings
	function getUser($field, $commentId, $userId)
	{
		if($field == 'quoteComments')
			$array = 'quoteCommentUserId';
		else if($field == 'paraphraseComments')
			$array = 'paraphraseCommentUserId';
		else if($field == 'musings')
			$array = 'musingUserId';
		$this->{$array}[$commentId] = $userId;
		if(array_key_exists($userId, $this->userArray))
			return;
		if($this->output == 'html')
			$this->userArray[$userId] = $this->user->displayUserAddEdit($userId);
		else if($this->output = 'rtf')
			$this->userArray[$userId] = $this->user->displayUserAddEdit($userId, FALSE, TRUE);
	}
// Format data for output
	function format($type)
	{
		$this->type = $type;
		if($this->output == 'html')
			return $this->formatHtml($type);
		if($this->output == 'rtf')
			return $this->formatRtf($type);
	}
	function formatHtml($type)
	{
		$titlePrinted = array();
		$index = 0;
		$pString = $string = FALSE;
		$first = TRUE;
		if(($type == 'quotes') && isset($this->quotes) && !empty($this->quotes))
		{
			foreach($this->quotes as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
					{
						$string = TABLE::tableStart(FALSE, 0, 0, 0, "left");
						$first = FALSE;
					}
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->formatTitle($resourceId);
					$index = 0;
				}
				foreach($array as $id => $text)
				{
					$class = $index % 2 ? 'alternate2' : 'alternate1';
					$pages = array_key_exists($id, $this->quotePages) ? $this->quotePages[$id] : FALSE;
					$this->citePages = $this->quoteCitePages[$id];
					$string .= $this->formatText($text, $resourceId, $id, FALSE, $class, 
						$pages, 'quoteComments');
					$index++;
				}
			}
			unset($this->quotes);
		}
		else if(($type == 'quoteComments') && isset($this->quoteComments) && !empty($this->quoteComments))
		{
			foreach($this->quoteComments as $resourceId => $array)
			{
				if(!empty($array) && !array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
					{
						$string = TABLE::tableStart(FALSE, 0, 0, 0, "left");
						$first = FALSE;
					}
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->formatTitle($resourceId);
					$index = 0;
				}
				foreach($array as $id => $comments)
				{
					foreach($comments as $commentId => $text)
					{
						$class = $index % 2 ? 'alternate2' : 'alternate1';
						$pages = array_key_exists($commentId, $this->quoteCommentPages) ? 
							$this->quoteCommentPages[$commentId] : FALSE;
						$this->citePages = FALSE;
						$string .= $this->formatText($text, $resourceId, $id, $commentId, $class, $pages, FALSE);
						$index++;
					}
				}
			}
			unset($this->quoteComments);
		}
		else if(($type == 'paraphrases') && isset($this->paraphrases) && !empty($this->paraphrases))
		{
			foreach($this->paraphrases as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
					{
						$string = TABLE::tableStart(FALSE, 0, 0, 0, "left");
						$first = FALSE;
					}
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->formatTitle($resourceId);
					$index = 0;
				}
				foreach($array as $id => $text)
				{
					$class = $index % 2 ? 'alternate2' : 'alternate1';
					$pages = array_key_exists($id, $this->paraphrasePages) ? 
						$this->paraphrasePages[$id] : FALSE;
					$this->citePages = $this->paraphraseCitePages[$id];
					$string .= $this->formatText($text, $resourceId, $id, FALSE, 
						$class, $pages, 'paraphraseComments');
					$index++;
				}
			}
			unset($this->paraphrases);
		}
		else if(($type == 'paraphraseComments') && isset($this->paraphraseComments) && 
			!empty($this->paraphraseComments))
		{
			foreach($this->paraphraseComments as $resourceId => $array)
			{
				if(!empty($array) && !array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
					{
						$string = TABLE::tableStart(FALSE, 0, 0, 0, "left");
						$first = FALSE;
					}
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->formatTitle($resourceId);
					$index = 0;
				}
				foreach($array as $id => $comments)
				{
					foreach($comments as $commentId => $text)
					{
						$class = $index % 2 ? 'alternate2' : 'alternate1';
						$pages = array_key_exists($commentId, $this->paraphraseCommentPages) ? 
							$this->paraphraseCommentPages[$commentId] : FALSE;
						$this->citePages = FALSE;
						$string .= $this->formatText($text, $resourceId, $id, $commentId, $class, $pages, FALSE);
						$index++;
					}
				}
			}
			unset($this->paraphraseComments);
		}
		else if(($type == 'musings') && isset($this->musings) && !empty($this->musings))
		{
			foreach($this->musings as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
					{
						$string = TABLE::tableStart(FALSE, 0, 0, 0, "left");
						$first = FALSE;
					}
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->formatTitle($resourceId);
					$index = 0;
				}
				foreach($array as $id => $text)
				{
					$class = $index % 2 ? 'alternate2' : 'alternate1';
					$pages = array_key_exists($id, $this->musingPages) ? $this->musingPages[$id] : FALSE;
					$this->citePages = FALSE;
					$string .= $this->formatText($text, $resourceId, $id, FALSE, $class, $pages, FALSE);
					$index++;
				}
			}
			unset($this->musings);
		}
		if($string)
		{
			$string .= TABLE::tableEnd();
			$pString = TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart() . 
			"&nbsp;" . MISC::p(MISC::h($this->messages->text("metadata", $type), 3)) . $string;
		}
		return $pString;
	}
	function formatRtf($type)
	{
		$titlePrinted = array();
		$pString = $string = FALSE;
		$first = TRUE;
		$class = FALSE;
		if(($type == 'quotes') && isset($this->quotes) && !empty($this->quotes))
		{
			foreach($this->quotes as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
						$first = FALSE;
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->wprtf->utf8_2_unicode($this->formatTitle($resourceId));
				}
				foreach($array as $id => $text)
				{
					$pages = array_key_exists($id, $this->quotePages) ? $this->quotePages[$id] : FALSE;
					$string .= $this->formatText($text, $resourceId, $id, FALSE, $class, 
						$pages, 'quoteComments');
				}
			}
			unset($this->quotes);
		}
		else if(($type == 'quoteComments') && isset($this->quoteComments) && !empty($this->quoteComments))
		{
			foreach($this->quoteComments as $resourceId => $array)
			{
				if(!empty($array) && !array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
						$first = FALSE;
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->wprtf->utf8_2_unicode($this->formatTitle($resourceId));
				}
				foreach($array as $id => $comments)
				{
					foreach($comments as $commentId => $text)
					{
						$pages = array_key_exists($commentId, $this->quoteCommentPages) ? 
							$this->quoteCommentPages[$commentId] : FALSE;
						$string .= $this->formatText($text, $resourceId, $id, $commentId, $class, $pages, FALSE);
					}
				}
			}
			unset($this->quoteComments);
		}
		else if(($type == 'paraphrases') && isset($this->paraphrases) && !empty($this->paraphrases))
		{
			foreach($this->paraphrases as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
						$first = FALSE;
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->wprtf->utf8_2_unicode($this->formatTitle($resourceId));
				}
				foreach($array as $id => $text)
				{
					$pages = array_key_exists($id, $this->paraphrasePages) ? 
						$this->paraphrasePages[$id] : FALSE;
					$string .= $this->formatText($text, $resourceId, $id, FALSE, 
						$class, $pages, 'paraphraseComments');
				}
			}
			unset($this->paraphrases);
		}
		else if(($type == 'paraphraseComments') && isset($this->paraphraseComments) && 
			!empty($this->paraphraseComments))
		{
			foreach($this->paraphraseComments as $resourceId => $array)
			{
				if(!empty($array) && !array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
						$first = FALSE;
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->wprtf->utf8_2_unicode($this->formatTitle($resourceId));
				}
				foreach($array as $id => $comments)
				{
					foreach($comments as $commentId => $text)
					{
						$pages = array_key_exists($commentId, $this->paraphraseCommentPages) ? 
							$this->paraphraseCommentPages[$commentId] : FALSE;
						$string .= $this->formatText($text, $resourceId, $id, $commentId, $class, $pages, FALSE);
					}
				}
			}
			unset($this->paraphraseComments);
		}
		else if(($type == 'musings') && isset($this->musings) && !empty($this->musings))
		{
			foreach($this->musings as $resourceId => $array)
			{
				if(!array_key_exists($resourceId, $titlePrinted))
				{
					if($first)
						$first = FALSE;
					$titlePrinted[$resourceId] = TRUE;
					$string .= $this->wprtf->utf8_2_unicode($this->formatTitle($resourceId));
				}
				foreach($array as $id => $text)
				{
					$pages = array_key_exists($id, $this->musingPages) ? $this->musingPages[$id] : FALSE;
					$string .= $this->formatText($text, $resourceId, $id, FALSE, $class, $pages, FALSE);
				}
			}
			unset($this->musings);
		}
		if($string)
		{
			if($this->output == 'html')
			{
				$string .= TABLE::tableEnd();
				$pString = TABLE::tdEnd() . TABLE::trEnd() . TABLE::trStart() . TABLE::tdStart() . 
				"&nbsp;" . MISC::p(MISC::h($this->messages->text("metadata", $type), 3)) . $string;
			}
			if($this->output == 'rtf')
			{
				$pString = "\n\n\\par\\par{\\b\\ul " . $this->messages->text("metadata", $type) . 
					"}\\par\\par\n\n" . $string;
			}
		}
		return $pString;
	}
// Format the resource heading
	function formatTitle($resourceId)
	{
		if($this->output == 'html')
		{
			$pString = TABLE::td($this->resourceTitles[$resourceId], 'metaResourceDetails', 
				FALSE, 'top');
			if($this->suwpCite)
				$pString .= TABLE::td("&nbsp;", 'metaResourceDetails', FALSE, 'top');
			else
				$pString .= TABLE::td(MISC::a($this->viewEditLink, $this->icons->view, 
					"index.php?action=resourceView" . htmlentities("&id=" . $resourceId . "&access=1")), 
					'metaResourceDetails', FALSE, 'top');
		}
		else if($this->output == 'rtf')
		{
			$pString = "{\\qc\n-------------------------------------------------------------------\n\\par\\par}";
			$pString .= "{\\qj\\li720\n" . $this->resourceTitles[$resourceId] . "\\par}\\par\n\n";
		}
		return $pString;
	}
// format metadata
	function formatText($text, $resourceId, $id, $commentId, $class, $pages, $commentsArray)
	{
		$user = FALSE;
		if($this->type == 'quoteComments')
		{
			$userIdArray = $this->quoteCommentUserId;
			if($this->session->getVar('setup_multiUser'))
				$user = $this->userArray[$userIdArray[$commentId]];
		}
		else if($this->type == 'paraphraseComments')
		{
			$userIdArray = $this->paraphraseCommentUserId;
			if($this->session->getVar('setup_multiUser'))
				$user = $this->userArray[$userIdArray[$commentId]];
		}
		else if($this->type == 'musings')
		{
			$userIdArray = $this->musingUserId;
			if($this->session->getVar('setup_multiUser'))
				$user = $this->userArray[$userIdArray[$id]];
		}
		if($this->output == 'html')
		{
			$pString = TABLE::trStart();
			$td = $this->cite->parseCitations($this->html->dbToHtmlTidy($text), $this->output);
			if(!empty($this->patterns))
				$td = preg_replace($this->patterns, MISC::span("$1", "highlight"), $td);
			$pString .= TABLE::td($pages . $td . "&nbsp;&nbsp;" . $user, $class);
			if($this->suwpCite) // Popup box for inserting metadata into SUWP
			{
				if(($this->type == 'musings') || ($this->type == 'quoteComments') || 
					($this->type == 'paraphraseComments'))
					$this->citePages = FALSE;
				if($this->radioButtonFirst)
				{
					$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex, TRUE);
					$this->radioButtonFirst = FALSE;
				}
				else
					$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex);
				$hidden = htmlspecialchars($this->convertBBCode(stripslashes($text)), ENT_QUOTES);
				if(($this->type == 'musings') || ($this->type == 'quoteComments') || 
					($this->type == 'paraphraseComments'))
				{
					$hidden = FORM::hidden("hidden_" . $this->citeIndex, $hidden);
					$hidden .= FORM::hidden("hiddenCiteTag_" . $this->citeIndex, '');
				}
				else
				{
					$citeTag = ' [cite]' . $resourceId . $this->citePages . '[/cite]';
					$hidden = FORM::hidden("hidden_" . $this->citeIndex, $hidden . $citeTag);
					$hidden .= FORM::hidden("hiddenCiteTag_" . $this->citeIndex, $citeTag);
				}
				$pString .= TABLE::td($hidden . $radio, $class, "right");
			}
			else
				$pString .= TABLE::td("&nbsp;", $class, "right");
			$pString .= TABLE::trEnd();
			++$this->citeIndex;
			if($commentsArray && !empty($this->$commentsArray) && 
				array_key_exists($resourceId, $this->$commentsArray) && 
				array_key_exists($id, $this->{$commentsArray}[$resourceId]))
			{
				if($this->type == 'quotes')
					$userIdArray = $this->quoteCommentUserId;
				else if($this->type == 'paraphrases')
					$userIdArray = $this->paraphraseCommentUserId;
				foreach($this->{$commentsArray}[$resourceId][$id] as $commentId => $comment)
				{
					$pString .= TABLE::trStart();
					if($this->session->getVar('setup_multiUser'))
						$user = "&nbsp;&nbsp;" . $this->userArray[$userIdArray[$commentId]];
					else
						$user = FALSE;
					$tdComment = $this->cite->parseCitations($this->html->dbToHtmlTidy($comment), $this->output);
					if(!empty($this->patterns))
						$tdComment = preg_replace($this->patterns, MISC::span("$1", "highlight"), $tdComment);
					$pString .= TABLE::td(MISC::b($this->messages->text("resources", 'comment')) . 
						":&nbsp;&nbsp;" . $tdComment . $user, $class);
					if($this->suwpCite)
					{
						$radio = FORM::radioButton(FALSE, 'cite', $this->citeIndex);
						$hidden = htmlspecialchars($this->convertBBCode(stripslashes($comment)), ENT_QUOTES);
						$hidden = FORM::hidden("hidden_" . $this->citeIndex, $hidden);
						$hidden .= FORM::hidden("hiddenCiteTag_" . $this->citeIndex, '');
						$pString .= TABLE::td($hidden . $radio, $class, "right");
					}
					else
						$pString .= TABLE::td("&nbsp;", $class, "right");
					$pString .= TABLE::trEnd();
					++$this->citeIndex;
				}
				unset($this->{$commentsArray}[$resourceId][$id]);
			}
		}
		if($this->output == 'rtf')
		{
			$pString = $pages . $this->convertRtf($text) . "\n\\par\\par\n\n";
// remove <span>...</span>from $user
			if($user)
				$pString .= preg_replace("/<span class=\"hint\">|<\/span>/i", '', $user) . "\n\\par\\par\n\n";
			if($commentsArray && !empty($this->$commentsArray) && 
				array_key_exists($resourceId, $this->$commentsArray) && 
				array_key_exists($id, $this->{$commentsArray}[$resourceId]))
			{
				if($this->type == 'quotes')
					$userIdArray = $this->quoteCommentUserId;
				else if($this->type == 'paraphrases')
					$userIdArray = $this->paraphraseCommentUserId;
				foreach($this->{$commentsArray}[$resourceId][$id] as $commentId => $comment)
				{
					if($this->session->getVar('setup_multiUser'))
					{
						$user = $this->userArray[$userIdArray[$commentId]];
						$user = str_replace("<span class=\"hint\">", '', $user);
						$user = str_replace("</span>", '', $user);
					}
					else
						$user = FALSE;
					$commentString = $this->convertRtf($comment) . "\n\\par\n\n";
					$pString .= "{\\qj\\li720\\ri720\n{\\b " . $this->messages->text("resources", 'comment') . 
						":}  " . $commentString . "\n" . $user . "\\par}\n\\par\\par\n\n";
				}
				unset($this->{$commentsArray}[$resourceId][$id]);
			}
		}
		return $pString;
	}
/************** RTF functions *****************/
/** Create RTF file
*/
	function createRtf($string)
	{
		include_once("core/file/FILE.php");
		$file = new FILE($this->db);
		include_once("core/file/export/EXPORTCOMMON.php");
		$common = new EXPORTCOMMON($this->db);
		include_once("core/messages/ERRORS.php");
		$errors = new ERRORS();
		$rtfString = $this->openRtf();
		$rtfString .= $string;
		$rtfString .= $this->closeRtf();
		list($fileName, $fullFileName) = $file->createFileName($string, '.rtf');
		if(!$fullFileName)
			return FALSE;
		if(!$fp = fopen("$fullFileName", "w"))
			return FALSE;
		if(!fputs($fp, $rtfString))
			return FALSE;
		fclose($fp);
		$common->writeFilenameToSession($fileName);
// Perform some system admin
		$file->tidyFiles();
		return $common->listFiles();
	}
/**
* Create the RTF opening tag
* @return string
*/
	function openRtf()
	{
		$string = "{\\rtf1\\ansi\\ansicpg1252\n";
// Stylesheet for hyperlinks, list bullets and endnotes
		$string .= "\n{\\stylesheet\n{\\*\\cs1 Hyperlink;}\n{\\*\\cs1 Bullet Symbols;}\n{\\*\\cs1 Numbering Symbols;}\n{\*\cs16 \additive \sbasedon10 endnote reference;}\n}\n" . "\\aftnnar\\fet1\n\n";
		$string .= "{\\qj\\li0\\ri0";
		return $string;
	}
/**
* Create the RTF closing tag
* @return string
*/
	function closeRtf()
	{
		return "}\n\\par\n\n}";
	}
// encode paragraphs from HTML
	function paragraphRtf($string)
	{
        return preg_replace("/<\/ br>/i", "__WIKINDX__NEWLINEPAR__", $string);
	}
// format RTF text with bold, italics, underline, convert newlines etc.
	function convertRtf($input)
	{
		$input = stripslashes($input);
		$input = str_replace("\\", "\\\\", $input);
		$input = str_replace("{", "\\{", $input);
		$input = str_replace("}", "\\}", $input);
// For lists, remove top level tags and leave [*] as list indicator
		$input = str_replace("[list]", "__WIKINDX__NEWLINEPAR__", $input);
		$input = str_replace("[/list]", "__WIKINDX__NEWLINEPAR__", $input);
// Remove certain BBCodes
		$pattern = array(
						"/\[size=.*?\](.*?)\[\/size\]/is",
						"/\[color=.*?\](.*?)\[\/color\]/is",
						"/\[float=.*?\](.*?)\[\/float\]/is",
						"/(\s*)(?<!\http:\/\/)(www\.)(\S+)/i", // watch out for 'www' in image/url tags!
						"/\[url\](.*?)\[\/url\]/is",
						"/\[url=(.*?)\](.*?)\[\/url\]/is",
						"/\[email\](.*?)\[\/email\]/is",
						"/(\s*)(ftp\.)(\S+)/i",
						"/\[img=.*?\](.*?)\[\/img\]/is",
						"/\[align=.*?\](.*?)\[\/align\]/is",
						"/\[code\](.*)\[\/code\]/is",
					);
		$change = array(
							"",
							"",
							"",
							"\\1{\\field{\\fldinst { HYPERLINK \"http://\\2\\3\" }}{\\fldrslt {\\cs1\\ul\\cf1 \\2\\3}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $1}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $2}}}__WIKINDX__NEWLINE__",
							"{\\field{\\fldinst { HYPERLINK \"mailto:$1\" }}{\\fldrslt {\\cs1\\ul\\cf1 $1}}}__WIKINDX__NEWLINE__",
							"\\1{\\field{\\fldinst { HYPERLINK \"http://\\2\\3\" }}{\\fldrslt {\\cs1\\ul\\cf1 \\2\\3}}}__WIKINDX__NEWLINE__",
							"",
							"",
							"",
						);
		$input = preg_replace($pattern, $change, $input);
// Handle images
		$input = preg_replace_callback("/\[img\](.*?)\[\/img\]/Usi",
			array($this->wprtf, "imageCallback"), $input);
// convert citations (FALSE for no hyperlink)
		$input = $this->cite->parseCitations($input, 'rtf', FALSE, TRUE);
		$pattern = array(
							"/\x0D\x0A|\x0D|\x0A/", // \r and \n
							"/\[b\](.*?)\[\/b\]/si",
							"/\[u\](.*?)\[\/u\]/si",
							"/\[i\](.*?)\[\/i\]/si",
							"/\[sup\](.*?)\[\/sup\]/si",
							"/\[sub\](.*?)\[\/sub\]/si",
						);
		$change = array(
							" __WIKINDX__NEWLINEPAR__", // temporary replace
							"{\\b $1}",
							"{\\ul $1}",
							"{\\i $1}",
							"{\\super $1}",
							"{\\sub $1}",
						);
		$input = preg_replace($pattern, $change, $input);
// Replace temporary newlines
		$input = str_replace("__WIKINDX__NEWLINEPAR__", "\\par\n", $input);
		$input = str_replace("__WIKINDX__NEWLINE__", "\n", $input);
		$input = $this->wprtf->utf8_2_unicode($input);
		return $input;
	}
/**
* Convert BBCode to design mode HTML for quotes and paraphrases for insertion into the SUWP.
* Some simplification occurs
*
* @author Mark Grimshaw
*/
	function convertBBCode($text)
	{
		$pattern = array(
							"/\[b\](.*?)\[\/b\]/si",
							"/\[u\](.*?)\[\/u\]/si",
							"/\[i\](.*?)\[\/i\]/si",
							"/\[sup\](.*?)\[\/sup\]/si",
							"/\[sub\](.*?)\[\/sub\]/si",
							"/\[size=(.*?)\](.*?)\[\/size\]/is",
							"/\[color=(.*?)\](.*?)\[\/color\]/is",
							"/(?<!\http:\/\/)(www\.)(\S+)/i", // watch out for 'www' in image/url tags!
							"/\[url\](.*?)\[\/url\]/is",
							"/\[url=(.*?)\](.*?)\[\/url\]/is",
							"/\[email\](.*?)\[\/email\]/is",
							"/(ftp\.)(\S+)/i",
							"/\[img\](.*?)\[\/img\]/is",
							"/\[list\](.*?)\[\/list\]/is",
							"/\[list.*?\](.*?)\[\/list\]/is",
							"/\[\*\]/is",
//							"/\[.*?\]|\[\/.*?\]/si",
						);
		$change = array(
							"<span style=\"font-weight: bold;\">$1</span>",
							"<span style=\"text-decoration: underline;\">$1</span>",
							"<span style=\"font-style: italic;\">$1</span>",
							"<sup>$1</sup>",
							"<sub>$1</sub>",
							"$2",
							"$2",
							"<a href=\"http://\\1\\2\">\\1\\2</a>",
							"<a href=\"$1\">$1</a>",
							"<a href=\"$1\">$2</a>",
							"<a href=\"mailto:$1\">$1</a>",
							"\\1\\2",
							"<img src=\"$1\" border=\"0\" />",
							"<ul>$1</ul>",
							"<ol>$1</ol>",
							"<li>",
//							"",
						);
		return preg_replace($pattern, $change, $text);
	}
}
?>
